<template>
  <el-card class="need-container">
    <el-row class="search">
      <el-col :span="24">
        <el-select v-model="searchArgs.status" multiple clearable placeholder="选择状态" size="mini">
          <el-option
            v-for="item in $requirementStatusList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
        <el-select v-model="searchArgs.appId" multiple clearable placeholder="选择应用" size="mini">
          <el-option
            v-for="item in appSelectList"
            :key="item.id"
            :label="item.appName"
            :value="item.appId"
          ></el-option>
        </el-select>
        <el-select v-model="searchArgs.bizId" multiple clearable placeholder="选择栏目" size="mini">
          <el-option
            v-for="item in bizSelectList"
            :key="item.id"
            :label="item.bizName"
            :value="item.bizId"
          ></el-option>
        </el-select>
        <el-select v-model="searchArgs.productCode" clearable placeholder="产品编码" size="mini">
          <el-option
            v-for="item in $productCodeList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
        <el-select v-model="searchArgs.orgCode" multiple clearable placeholder="集团/省份" size="mini">
          <el-option v-for="(value, key) in orgCodeObj" :key="key" :label="value" :value="key"></el-option>
        </el-select>
        <el-input v-model="searchArgs.requirementName" class="name" size="mini">
          <template slot="prepend">需求名称</template>
        </el-input>
        <el-button type="primary" size="mini" @click="handleSearch">查询</el-button>
        <el-button type="primary" size="mini" class="add-btn" @click="handleOpen">新建需求</el-button>
      </el-col>
    </el-row>
    <div>
      <el-table v-loading="tableLoading" size="mini" border :data="tableData" style="width: 100%">
        <el-table-column
          v-for="item in columns"
          :key="item.prop"
          :prop="item.prop"
          :label="item.label"
          :show-overflow-tooltip="true"
          :sortable="item.sortable"
          :min-width="item.width"
        >
          <template slot-scope="scope">
            <span v-if="item.prop === 'status'">{{$requirementStatusObj[scope.row.status] || "--"}}</span>
            <span v-else-if="item.prop === 'sdkType'">{{$sdkTypeObj[scope.row.sdkType] || "--"}}</span>
            <span v-else-if="item.prop === 'productCode'">{{$productCodeObj[scope.row.productCode] || "--"}}</span>
            <span v-else>
              {{scope.row[item.prop] || "--"}}
              <br>
            </span>
          </template>
        </el-table-column>
        <el-table-column
          prop="createTime"
          label="创建时间"
          min-width="140"
          :show-overflow-tooltip="true"
        >
          <template
            slot-scope="scope"
          >{{$moment(scope.row["createTime"]).format("YYYY-MM-DD HH:MM:SS")}}</template>
        </el-table-column>
        <el-table-column
          prop="updateTime"
          label="更新时间"
          min-width="140"
          :show-overflow-tooltip="true"
        >
          <template
            slot-scope="scope"
          >{{$moment(scope.row["updateTime"]).format("YYYY-MM-DD HH:MM:SS")}}</template>
        </el-table-column>
        <el-table-column label="操作" width="100">
          <template slot-scope="scope">
            <el-button size="mini" type="text" @click="handleDetail(scope)">查看</el-button>
            <el-button
              v-if="scope.row['status'] <2 "
              size="mini"
              type="text"
              @click="handleEdit(scope)"
            >编辑</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="pageSize"
        background
        layout="total, prev, pager, next, sizes, jumper"
        :total="total"
      ></el-pagination>
    </div>
    <el-drawer
      class="flex-el-drawer"
      :with-header="false"
      :visible.sync="drawer"
      custom-class="demo-drawer"
      size="40%"
      direction="rtl"
      ref="drawer"
    >
      <div class="el-drawer__header">
        <div>
          <span>添加需求</span>
        </div>
        <button class="el-drawer__close-btn" @click="handleClose">
          <el-icon class="el-icon-close"></el-icon>
        </button>
      </div>
      <div class="el-drawer-content">
        <el-form
          ref="form"
          :rules="formRules"
          :model="form"
          label-width="130px"
          size="mini"
          label-position="top"
        >
          <el-form-item label="应用" prop="appId">
            <el-select
              v-model="form.appId"
              placeholder="请选择应用"
              value-key="appId"
              @change="handleChangeApp"
            >
              <el-option
                v-for="item in appSelectList"
                :key="item.appId"
                :label="item.appName"
                :value="item"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="栏目" prop="bizId">
            <el-select v-model="form.bizId" placeholder="请选择栏目">
              <el-option
                v-for="item in bizList"
                :key="item.bizId"
                :label="item.bizName"
                :value="item.bizId"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="埋点SDK类型" prop="sdkType">
            <el-select v-model="form.sdkType" placeholder="请选择埋点SDK类型" @change="handleChangeSdk">
              <el-option
                v-for="item in sdkTypeList"
                :label="item.label"
                :key="item.value"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="SDK产品编码" prop="productCode">
            <el-select v-model="form.productCode" placeholder="请选择SDK产品编码">
              <el-option
                v-for="item in $productCodeList"
                :label="item.label"
                :key="item.value"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="需求名称" prop="requirementName">
            <el-input v-model="form.requirementName" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="系统版本" prop="versionId">
            <el-select v-model="form.versionId" placeholder="请选择版本">
              <el-option
                v-for="item in versionList"
                :label="item.version"
                :key="item.id"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <div slot="label">
              复制其他需求的埋点
              <el-tooltip content="请选择栏目、sdk类型、产品编码" placement="top">
                <i class="el-icon-question"></i>
              </el-tooltip>
            </div>
            <el-select
              @visible-change="handleQuerySyncList"
              v-model="form.targetId"
              placeholder="请选择需求"
            >
              <el-option
                v-for="item in syncList"
                :label="item.requirementName"
                :key="item.id"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="描述" prop="desc">
            <el-input type="textarea" v-model="form.desc"></el-input>
          </el-form-item>
        </el-form>
      </div>
      <div class="el-drawer-footer">
        <el-button size="mini" type="text" @click="handleClose">关闭</el-button>
        <el-button
          size="mini"
          type="primary"
          @click="handleConfirm"
          :loading="drawerLoading"
        >{{ drawerLoading ? '提交中' : '保存并编辑' }}</el-button>
      </div>
    </el-drawer>
  </el-card>
</template>

<script>
export default {
  name: "needList",
  data() {
    return {
      drawer: false,
      drawerLoading: false,
      tableLoading: false,
      form: {
        appId: "",
        bizId: "",
        sdkType: "",
        productCode: "",
        requirementName: "",
        versionId: "",
        targetId: ""
      },
      formRules: {
        requirementName: [
          { required: true, message: "请输入需求名称", trigger: "blur" }
        ],
        appId: [{ required: true, message: "请选择应用", trigger: "change" }],
        bizId: [{ required: true, message: "请选择栏目", trigger: "change" }],
        productCode: [
          { required: true, message: "请选择产品编码", trigger: "change" }
        ],
        sdkType: [
          { required: true, message: "请选择sdk类型", trigger: "change" }
        ],
        versionId: [
          { required: true, message: "请选择系统版本", trigger: "change" }
        ]
      },
      currentPage: 1,
      pageSize: 10,
      total: 0,
      searchArgs: {
        status: [],
        appId: [],
        bizId: [],
        orgCode: []
      },
      bizObj: {}, // 应用、栏目联动
      syncList: [],
      versionList: [],
      productList: [],
      sdkTypeList: [],
      columns: [
        {
          prop: "requirementId",
          label: "需求ID",
          width: 60
          // sortable: true
        },
        {
          prop: "requirementName",
          label: "需求名称",
          width: 100
          // sortable: true
        },
        {
          prop: "appName",
          label: "应用名称",
          width: 100
          // sortable: false
        },
        {
          prop: "bizName",
          label: "栏目",
          width: 80
          // sortable: true
        },
        {
          prop: "version",
          label: "系统版本",
          width: 80
          // sortable: true
        },
        {
          prop: "sdkType",
          label: "埋点SDK类型",
          width: 100
          // sortable: true
        },
				{
					prop: "productCode",
					label: "SDK产品编码",
					width: 100
				},
        {
          prop: "status",
          label: "状态",
          width: 80
          // sortable: true
        },
        {
          prop: "creatorName",
          label: "负责人",
          width: 80
          // sortable: true
        }
      ],
      tableData: []
    };
  },
  created() {
    this.$store.dispatch("getOrgList");
    this.$store.dispatch("getAppSelectList");
    this.$store.dispatch("getBizSelectList", {
      hasEventCollectData: false,
      needSimpleData: true
    });
    this.handleQueryList();
  },
  mounted() {},
  computed: {
    appSelectList() {
      return this.$store.state.publicData.appSelectList;
    },
    orgCodeObj() {
      return this.$store.state.publicData.orgCodeObj;
    },
    bizSelectList() {
      return this.$store.state.publicData.bizSelectList;
    },
    bizList() {
      return this.$store.state.publicData.bizList;
    }
  },
  watch: {
    bizList(val) {
      val.forEach(item => {
        if (!this.bizObj[item.appId]) {
          this.bizObj[item.appId] = {
            appId: item.appId,
            appName: item.appName,
            bizList: []
          };
        }
        this.bizObj[item.appId].bizList.push(item);
      });
    }
  },
  methods: {
    // 点击查询
    handleSearch() {
      this.currentPage = 1;
      this.handleQueryList();
    },
    // 查询列表
    async handleQueryList() {
      this.tableLoading = true;
      try {
        let data = Object.assign({}, this.searchArgs, {
          currentPage: this.currentPage,
          pageSize: this.pageSize
        });
        let res = await this.$requirementApi.requirementList(data);
        if (res) {
          let { list, total } = res.value;
          this.total = total;
          this.tableData = list;
        }
        this.tableLoading = false;
      } catch (e) {
        this.tableLoading = false;
      }
    },
    // 应用改变，栏目列表改变，sdk类型改变，默认产品编码改变
    handleChangeApp(item) {
      this.sdkTypeList = [];
      this.form.sdkType = "";
      this.form.versionId = "";
      this.form.bizId = "";
      let { appId, appType, productCode } = item;
      switch (appType) {
        case 1:
          this.sdkTypeList = this.$sdkTypeList.slice(0, 3);
          break;
        case 2:
          this.sdkTypeList = this.$sdkTypeList.slice(2, 3);
          break;
        case 3:
          this.sdkTypeList = this.$sdkTypeList.slice(-1);
          break;
        default:
          break;
      }
      this.form.productCode = productCode;
      this.handleQueryVersionList(appId);
      this.$store.dispatch("getBizList", {
        appId,
        hasEventCollectData: false,
        needSimpleData: true
      });
    },
    // 选择sdkType
    handleChangeSdk() {
      this.form.targetId = "";
      this.syncList = [];
    },
    // 版本列表
    async handleQueryVersionList(appId) {
      this.versionList = [];
      let data = {
        appId
      };
      let res = await this.$requirementApi.versionList(data);
      if (res) {
        let { list } = res.value;
        this.versionList = list;
      }
    },
    // 同步需求列表
    async handleQuerySyncList(v) {
      if (!v || this.syncList.length > 0) {
        return;
      }
      this.syncList = [];
      let { bizId, sdkType, productCode } = this.form;
      let data = {
        bizId,
        sdkType,
        productCode
      };
      let res = await this.$requirementApi.requirementSyncList(data);
      if (res) {
        this.syncList = res.value.list;
      }
    },
    // 查看详情
    handleDetail(scope) {
      let { id } = scope.row;
      this.$router.push({ path: `/buryNeed/detail/${escape(id)}` });
    },
    // 编辑
    handleEdit(scope) {
      let { id } = scope.row;
      this.$router.push({ path: "/buryNeed/edit/" + escape(id) });
    },
    handleCurrentChange(current) {
      this.currentPage = current;
      this.handleQueryList();
    },
    handleSizeChange(size) {
      this.currentPage = 1;
      this.pageSize = size;
      this.handleQueryList();
    },
    // drawer：打开
    handleOpen() {
      this.drawer = true;
    },
    // 关闭
    handleClose() {
      this.drawerLoading = true;
      this.$refs.form.resetFields();
      this.drawer = false;
      this.drawerLoading = false;
    },
    // 保存并编辑
    handleConfirm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.handleSave();
        } else {
          return false;
        }
      });
    },
    async handleSave() {
      let res = await this.$requirementApi.requirementAdd(this.form);
      if (res.success) {
        let { value } = res;
        this.$router.push({
          path: `/buryNeed/edit/${escape(value)}`
        });
      }
    }
  }
};
</script>

<style lang="scss">
.need-container {
  .name {
    width: 250px;
    margin: 0 10px 0 5px;
  }

  .search {
    .el-select {
      width: 120px;
      margin: 0 5px;
    }

    .add-btn {
      float: right;
    }
  }

  .demo-drawer__content {
    padding: 20px 16px;
  }
}
</style>
